<?php
namespace app\admin\controller\Sys\middleware;
use app\admin\controller\Sys\model\Menu;
use app\admin\controller\Sys\model\Application;
use app\admin\controller\Sys\model\Field;
use app\admin\controller\Sys\model\Action;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use think\facade\Db;


class deleteApplication implements MiddlewareInterface
{
	
    public function process(Request $request, callable $handler) : Response
    {	
		$data = $request->post();
		
		$applicationInfo = Application::find($data['app_id']);
		
		$rootPath = base_path();
		
		if($applicationInfo['app_dir']){
			is_dir($rootPath.'/app/'.$applicationInfo['app_dir']) && remove_dir($rootPath.'/app/'.$applicationInfo['app_dir']);
			is_dir($rootPath.'/public/components/'.$applicationInfo['app_dir']) && remove_dir($rootPath.'/public/components/'.$applicationInfo['app_dir']);
			is_dir($rootPath.'/route/'.$applicationInfo['app_dir']) && remove_dir($rootPath.'/route/'.$applicationInfo['app_dir']);
			@unlink($rootPath.'/route/app/'.$applicationInfo['app_dir'].'.php');
		}
		$where['menu_id'] = Menu::where(['app_id'=>$data['app_id']])->column('menu_id');
		
		Menu::where(['app_id'=>$data['app_id']])->delete();
		Field::where($where)->delete();
		Action::where($where)->delete();
		
		return $handler($request);
		
		
    }
}